package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.R;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api(description = "微信登录接口")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 获取微信登录参数
     */
    @ApiOperation(value = "获取微信登录参数")
    @GetMapping("getLoginParam")
    @ResponseBody
    public R genQrConnect(HttpSession session) throws UnsupportedEncodingException {
        Map<String,Object> map = new HashMap<>();
        String redirectUrl = URLEncoder
                .encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL,"UTF-8");
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("redirectUri", redirectUrl);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis()+"");//System.currentTimeMillis()+""
        return R.ok().data(map);
    }

    @ApiOperation(value = "实现微信登录回调")
    @GetMapping("callback")
    public String  callback(String code, String state, HttpSession session) {
        //1获取参数临时票据code
        System.out.println("code = " + code);
        System.out.println("state = " + state);
        //2拿code换取参数access token，openid
        //2.1拼写URL
        //方式一
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
//                "?appid=APPID&secret=SECRET&code=CODE" +
//                "&grant_type=authorization_code";
        //方式二
        StringBuffer urlBuffer=new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(
                urlBuffer.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code
        );
        try {
            //2.2 发送请求拿响应
            String accessTokenStr = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenStr = " + accessTokenStr);
            //2.3转化响应数据，获取关键参数
            JSONObject jsonObject = JSONObject.parseObject(accessTokenStr);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            System.out.println("access_token = " + access_token);
            System.out.println("openid = " + openid);
            //3 根据openid查询用户信息
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("openid",openid);
            UserInfo userInfo = userInfoService.getOne(wrapper);
            //4 用户信息为空，走注册步骤
            if (userInfo==null){
                //4.1调用微信接口，拿access_token、openid换取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl =
                        String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultInfo:"+resultInfo);
                //4.2 转化响应，获取参数
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                //解析用户信息
                //用户昵称
                String nickname = resultUserInfoJson.getString("nickname");
                //用户头像
                String headimgurl = resultUserInfoJson.getString("headimgurl");
                userInfo = new UserInfo();
                userInfo.setOpenid(openid);
                userInfo.setNickName(nickname);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);

            }
            //5 用户信息不为空，走登录（判断是否绑定手机号）
            //5.1验证用户是否被锁定
            if(userInfo.getStatus()==0){
                throw  new YyghException(20001,"用户已经被禁用");
            }

            //5.2补全信息
            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name",name);
            //5.3判断是否绑定手机号
            //如果绑定了手机号，openid=""
            //没有绑定手机号，openid=获取的微信参数openid
            String phone=  userInfo.getPhone();
            if (StringUtils.isEmpty(phone)){
                map.put("openid",userInfo.getOpenid());
            }else {
                map.put("openid","");
            }
            //5.4获取token
            String token =
                    JwtHelper.createToken(userInfo.getId(), userInfo.getName());
            map.put("token",token);
            //6重定向页面
            return "redirect:http://localhost:3000/weixin/callback?token="+
                    map.get("token")+ "&openid="
                    +map.get("openid")+"&name="
                    +URLEncoder.encode((String) map.get("name"),"utf-8");

        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(20001,"微信扫码登录失败");
        }
    }
    }
